<script setup lang="ts">
defineOptions({
  name: "CollectMaterials"
});

import { ref, onMounted, reactive } from "vue";
import { ElButton, ElInput, ElTable, ElTableColumn, ElPagination, ElTag, ElMessage, ElMessageBox, ElDialog, ElSelect, ElOption, ElForm, ElFormItem, ElLoading, ElCol, ElRow, ElTabs, ElTabPane, ElIcon } from "element-plus";
import { Search, Plus } from "@element-plus/icons-vue";
import { getRepairReportList } from "../../../api/repair";
import type { RepairReportListVo, RepairReportQueryDto } from "../../../api/repair";
import { findAllCells } from "@/api/cell";
import type { Cell } from "@/api/cell";
import { getRepositoryList } from "@/api/repository";
import { getInventoryMaterialList } from "@/api/inventoryFlow";
import { addCollectMaterial, getCollectMaterialList } from "../../../api/collectMaterials";
import type { CollectMaterialPayload } from "../../../api/collectMaterials";

// 搜索关键词
const searchKeyword = ref("");
const contactPhone = ref("");
const selectedCellId = ref(0);

// 分页数据
const currentPage = ref(1);
const pageSize = ref(10);
const totalCount = ref(0);
const loading = ref(false);

// 维修退遗费数据列表
const collectMaterials = ref<RepairReportListVo[]>([]);

// 小区数据
interface CommunityOption {
  label: string;
  value: number;
}
const communities = ref<CommunityOption[]>([{ label: "全部", value: 0 }]);

// 加载小区数据
const loadCellData = async () => {
  try {
    console.log("开始加载小区数据");
    const response = await findAllCells();
    console.log("小区数据请求响应:", response);
    if (response.code === 0 || response.code === 200) {
      const cells = response.data || [];
      console.log("加载到的小区数量:", cells.length);
      const newCommunities = [
        { label: "全部", value: 0 },
        ...cells.map((cell: Cell) => ({
          label: cell.name,
          value: cell.id
        }))
      ];
      communities.value = newCommunities;
    } else {
      console.error(
        "获取小区数据失败，错误码:",
        response.code,
        "错误信息:",
        response.message
      );
    }
  } catch (error) {
    console.error("获取小区数据失败:", error);
    ElMessage.error("获取小区数据失败");
  }
};

// 加载维修退遗费数据
const loadCollectMaterialsData = async () => {
  loading.value = true;
  try {
    const queryData: RepairReportQueryDto = {
      page: currentPage.value,
      limit: pageSize.value,
      keyword: searchKeyword.value,
      contactPhone: contactPhone.value,
      cellId: selectedCellId.value === 0 ? undefined : selectedCellId.value
    };

    console.log("正在请求维修退遗费数据:", queryData);
    const response = await getRepairReportList(queryData);
    console.log("维修退遗费数据请求响应:", response);

    if (response.code === 0 || response.code === 200) {
      collectMaterials.value = response.data?.list || [];
      totalCount.value = response.data?.total || 0;
      console.log("加载到的维修退遗费数据数量:", collectMaterials.value.length);
    } else {
      console.error("获取维修退遗费数据失败，错误码:", response.code, "错误信息:", response.message);
      ElMessage.error(response.message || "获取维修退遗费数据失败");
    }
  } catch (error) {
    console.error("获取维修退遗费数据失败:", error);
    ElMessage.error("获取维修退遗费数据失败");
  } finally {
    loading.value = false;
  }
};

// 搜索方法
const handleSearch = () => {
  currentPage.value = 1; // 搜索时重置到第一页
  loadCollectMaterialsData();
};

// 重置搜索
const handleReset = () => {
  searchKeyword.value = "";
  contactPhone.value = "";
  selectedCellId.value = 0;
  currentPage.value = 1;
};

// 页码变化
const handlePageChange = (val: number) => {
  currentPage.value = val;
  loadCollectMaterialsData();
};

// 每页条数变化
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  currentPage.value = 1;
  loadCollectMaterialsData();
};

// 模态框状态
const collectMaterialDialogVisible = ref(false);
const returnMaterialDialogVisible = ref(false);

// 当前选中的维修记录
const selectedRepairRecord = ref<RepairReportListVo | null>(null);

// 材料项接口
interface MaterialItem {
  id: string;
  name: string;
  brand: string;
  specification: string;
  unit: string;
  referencePrice?: number;
  stock?: number;
  quantity: number;
  returnQuantity?: number;
  usedQuantity?: number;
  returnedQuantity?: number;
  remark?: string;
  repositoryId?: string;
  materialId?: string;
  stockQuantity?: number;
}

// 退料材料数据
interface ReturnMaterialItem extends MaterialItem {
  usedQuantity: number;
  returnedQuantity: number;
  availableQuantity?: number; // 可退数量
}

// 材料列表数据
const materialsList = ref<MaterialItem[]>([]);
// 仓库列表
const repositoryList = ref<any[]>([]);
// 选中的仓库ID
const selectedRepositoryId = ref<string>('');
// 材料选择对话框
const materialSelectDialogVisible = ref<boolean>(false);
// 库存材料列表
const inventoryMaterials = ref<any[]>([]);
// 搜索材料关键词
const materialSearchKeyword = ref<string>('');
// 已选中的材料ID列表
const selectedMaterialIds = ref<Set<string>>(new Set());

// 可退材料数据 - 初始为空数组，将通过API加载
const returnableMaterials = ref<ReturnMaterialItem[]>([]);

// 已退材料数据
const returnedMaterials = ref<ReturnMaterialItem[]>([]);

// 退料选项卡
const activeReturnTab = ref('returnable');

// 打开领料对话框
const openCollectMaterialDialog = (row: RepairReportListVo) => {
  selectedRepairRecord.value = row;
  collectMaterialDialogVisible.value = true;
};

// 打开退料对话框并加载可退材料数据
const openReturnMaterialDialog = async (row: RepairReportListVo) => {
  selectedRepairRecord.value = row;
  
  // 使用专门的函数加载可退材料数据
  await reloadReturnableMaterials(row.id);
  
  // 打开对话框
  returnMaterialDialogVisible.value = true;
};

// 添加材料
const addMaterial = () => {
  if (!selectedRepositoryId.value) {
    ElMessage.warning('请先选择仓库');
    return;
  }
  // 加载该仓库的库存材料
  loadInventoryMaterials();
  // 清空已选中的材料ID
  selectedMaterialIds.value.clear();
  // 打开材料选择对话框
  materialSelectDialogVisible.value = true;
};

// 加载仓库列表
const loadRepositories = async () => {
  try {
    const response = await getRepositoryList({ page: 1, limit: 100 });
    repositoryList.value = response.data?.list || [];
  } catch (error) {
    ElMessage.error('加载仓库列表失败');
    console.error('Failed to load repositories:', error);
  }
};

// 加载库存材料列表
const loadInventoryMaterials = async () => {
  try {
    const response = await getInventoryMaterialList({
      repositoryId: selectedRepositoryId.value,
      name: materialSearchKeyword.value,
      page: 1,
      limit: 100
    });
    inventoryMaterials.value = response.data?.records || response.data?.list || [];
  } catch (error) {
    ElMessage.error('加载库存材料失败');
    console.error('Failed to load inventory materials:', error);
  }
};

// 处理表格选择变化
const handleSelectionChange = (selection: any[]) => {
  selectedMaterialIds.value.clear();
  selection.forEach(item => {
    selectedMaterialIds.value.add(item.materialId.toString());
  });
};

// 处理材料选择
const handleMaterialSelection = () => {
  inventoryMaterials.value.forEach(material => {
    if (selectedMaterialIds.value.has(material.materialId.toString())) {
      // 检查是否已存在该材料
      const existingIndex = materialsList.value.findIndex(
        item => item.materialId === material.materialId.toString()
      );
      
      if (existingIndex === -1) {
        const newMaterial: MaterialItem = {
          id: Date.now().toString(),
          name: material.name,
          brand: material.brand,
          specification: material.specification,
          unit: material.unit,
          referencePrice: material.outboundPrice,
          quantity: 0,
          repositoryId: selectedRepositoryId.value.toString(),
          materialId: material.materialId.toString(),
          stocks: material.stocks
        };
        materialsList.value.push(newMaterial);
      }
    }
  });
  materialSelectDialogVisible.value = false;
};

// 移除材料
const removeMaterial = (id: string) => {
  const index = materialsList.value.findIndex(item => item.id === id);
  if (index !== -1) {
    materialsList.value.splice(index, 1);
  }
};

// 当前正在处理的退料材料
const currentReturnMaterial = ref<ReturnMaterialItem | null>(null);
// 退料详情对话框可见性
const returnDetailDialogVisible = ref(false);
// 用户输入的退货数量
const inputReturnQuantity = ref(0);
// 退货金额
const returnAmount = ref(0);

// 打开退料详情对话框
const openReturnDetailDialog = (item: ReturnMaterialItem) => {
  currentReturnMaterial.value = { ...item };
  // 设置可退数量为后端返回的quantity字段
  currentReturnMaterial.value.availableQuantity = item.quantity || item.usedQuantity;
  
  // 从已退材料列表中查找是否有该材料的退料记录
  const returnedItem = returnedMaterials.value.find(m => m.id === item.id);
  if (returnedItem) {
    // 如果有退料记录，使用已退材料的退货数量
    inputReturnQuantity.value = returnedItem.returnedQuantity;
    // 保留备注信息
    currentReturnMaterial.value.remark = returnedItem.remark;
  } else {
    // 如果没有退料记录，使用可退材料中可能存在的returnedQuantity或默认为1
    inputReturnQuantity.value = item.returnedQuantity || 1;
  }
  
  // 计算初始退货金额
  calculateReturnAmount();
  returnDetailDialogVisible.value = true;
};

// 计算退货金额
const calculateReturnAmount = () => {
  if (currentReturnMaterial.value && currentReturnMaterial.value.price) {
    returnAmount.value = Number(currentReturnMaterial.value.price) * inputReturnQuantity.value;
  } else {
    returnAmount.value = 0;
  }
};

// 确认退料
const confirmReturnMaterial = () => {
  if (!currentReturnMaterial.value) return;
  
  // 验证退货数量
  if (inputReturnQuantity.value <= 0) {
    ElMessage.warning('请输入有效的退货数量');
    return;
  }
  
  if (inputReturnQuantity.value > currentReturnMaterial.value.availableQuantity!) {
    ElMessage.warning('退货数量不能大于可退数量');
    return;
  }
  
  // 将材料信息添加到已退列表，但保留在可退列表中
  const index = returnableMaterials.value.findIndex(m => m.id === currentReturnMaterial.value!.id);
  if (index !== -1) {
    const returnedItem = { 
      ...returnableMaterials.value[index], 
      returnedQuantity: inputReturnQuantity.value,
      quantity: inputReturnQuantity.value, // 设置为调用API时传递给后端的quantity
      remark: currentReturnMaterial.value.remark // 保留备注信息
    };
    
    // 检查已退材料列表中是否已存在该材料
    const existingReturnedIndex = returnedMaterials.value.findIndex(m => m.id === currentReturnMaterial.value!.id);
    if (existingReturnedIndex !== -1) {
      // 如果已存在，则更新现有记录
      returnedMaterials.value[existingReturnedIndex] = returnedItem;
    } else {
      // 如果不存在，则添加新记录
      returnedMaterials.value.push(returnedItem);
    }
    
    // 同时更新可退材料中的returnedQuantity，以便在UI中正确显示
    returnableMaterials.value[index].returnedQuantity = inputReturnQuantity.value;
    
    // 不再显示退料成功消息，只在保存时显示
    returnDetailDialogVisible.value = false;
    // 不再重置数据，以便下次打开对话框时能回显之前选择的数量
    // 但需要清除当前处理的材料引用，避免影响其他操作
    currentReturnMaterial.value = null;
  }
};

// 更新退货数量并重新计算金额
const updateReturnQuantity = (value: number) => {
  inputReturnQuantity.value = value;
  calculateReturnAmount();
};

// 一键退料功能
const batchReturnMaterial = () => {
  // 将所有可退材料移动到已退材料列表
  const materialsToReturn = [...returnableMaterials.value];
  materialsToReturn.forEach(item => {
    item.returnedQuantity = item.returnQuantity || item.usedQuantity;
    returnedMaterials.value.push(item);
  });
  returnableMaterials.value = [];
  ElMessage.success('一键退料成功');
};

// 一键删除已退材料功能
const batchDeleteReturned = () => {
  ElMessageBox.confirm('确定要删除所有已退材料吗？', '确认删除', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    returnedMaterials.value = [];
    ElMessage.success('已退材料删除成功');
  }).catch(() => {
    // 用户取消删除
  });
};

// 保存领料
const saveCollectMaterials = async () => {
  try {
    // 构造请求参数，完全按照接口要求的字段名，添加仓库ID
    const payload = {
      repairReportsId: selectedRepairRecord.value?.id,
      repositoryId: Number(selectedRepositoryId.value), // 添加所选仓库ID
      status: 0, // 按照要求，领料页面调用时传递status为0
      materialPriceList: materialsList.value
        .filter(item => item.quantity > 0) // 只包含数量大于0的材料
        .map(item => ({
          materialId: Number(item.materialId),
          price: Number(item.referencePrice || 0),
          quantity: Number(item.quantity)
        }))
    };
    
    // 调用API
    const response = await addCollectMaterial(payload);
    
    if (response.code === 0 || response.code === 200) {
      ElMessage.success('领料成功');
      collectMaterialDialogVisible.value = false;
      // 可以在这里重置材料列表或刷新数据
      materialsList.value = [];
    } else {  
      ElMessage.error(response.message || '领料失败');
    }
  } catch (error) {
    console.error('保存领料失败:', error);
    ElMessage.error('网络错误，请稍后重试');
  }
};

// 处理退料对话框取消
const handleCancelReturn = () => {
  // 重置退料数据
  returnedMaterials.value = [];
  returnableMaterials.value = [];
  inputReturnQuantity.value = 0;
  returnAmount.value = 0;
  currentReturnMaterial.value = null;
  
  // 关闭对话框
  returnMaterialDialogVisible.value = false;
};

// 重新加载可退材料数据的函数
const reloadReturnableMaterials = async (repairReportId: string | number) => {
  try {
    ElLoading.service({ text: '加载材料数据中...' });
    
    // 调用查询维修退遗费列表API获取材料数据，增加limit以获取更多数据
    const response = await getCollectMaterialList({
      page: 1,
      limit: 100, // 增加limit值以确保能获取所有相关材料
      repairReportsId: repairReportId
    });
    
    console.log('API返回的材料数据:', response);
    
    if (response.code === 0 || response.code === 200) {
      // 处理返回的数据，将其转换为ReturnMaterialItem格式
      // 检查是否有records字段，兼容不同格式的API返回
      const materialsData = response.data?.list || response.data?.records || [];
      
      console.log('处理前的原始数据:', materialsData);
      
      // 转换数据格式，注意字段映射和兼容处理
      const processedMaterials = materialsData.map((item: any) => ({
        id: item.id?.toString() || Date.now().toString(),
        name: item.name,
        brand: item.brand,
        specification: item.specification,
        unit: item.unit,
        quantityIssued: item.quantityIssued || item.usedQuantity || 0, // 兼容新旧字段名
        quantity: item.quantity || 0, // 可退数量
        quantityReturned: item.quantityReturned || item.returnedQuantity || 0, // 兼容新旧字段名
        materialId: item.materialId?.toString(),
        price: item.price || 0,
        remark: item.remark || ''
      }));
      
      console.log('处理后的数据:', processedMaterials);
      
      // 分离可退材料和已退材料
      // 优化可退材料的过滤条件，确保能正确显示可退材料
      returnableMaterials.value = processedMaterials.filter(item => 
        item.quantityIssued > 0 // 只要有发放数量就认为是可退材料
      );
      
      // 已退材料：有已退数量的材料
      returnedMaterials.value = processedMaterials.filter(item => 
        (item.quantityReturned || 0) > 0
      );
      
      console.log('可退材料数量:', returnableMaterials.value.length);
      console.log('已退材料数量:', returnedMaterials.value.length);
    } else {
      ElMessage.error('加载材料数据失败: ' + (response.message || '未知错误'));
    }
  } catch (error) {
    console.error('加载材料数据失败:', error);
    ElMessage.error('网络错误，请稍后重试');
  } finally {
    ElLoading.service().close();
  }
};

// 保存退料
const saveReturnMaterials = async () => {
  // 检查是否有已退材料
  if (returnedMaterials.value.length === 0) {
    ElMessage.warning('请先选择要退的材料');
    return;
  }
  
  try {
    ElLoading.service({ text: '保存退料信息中...' });
    
    // 构造请求参数，按照接口要求的格式，添加仓库ID
    // 用户填写的退货数量对应传递的quantity
    const payload = {
      repairReportsId: selectedRepairRecord.value?.id,
      repositoryId: Number(selectedRepositoryId.value), // 添加所选仓库ID
      status: 1, // 退料状态设为1
      materialPriceList: returnedMaterials.value.map(item => ({
        materialId: Number(item.materialId),
        price: Number(item.price || 0),
        quantity: Number(item.returnedQuantity) // 用户填写的退货数量
      }))
    };
    
    // 调用添加维修退遗费API
    const response = await addCollectMaterial(payload);
    
    if (response.code === 0 || response.code === 200) {
      ElMessage.success('退料保存成功');
      
      // 重置退料数据
      returnedMaterials.value = [];
      returnableMaterials.value = [];
      inputReturnQuantity.value = 0;
      returnAmount.value = 0;
      currentReturnMaterial.value = null;
      
      // 关闭对话框
      returnMaterialDialogVisible.value = false;
      
      // 不再重新加载数据，避免干扰用户操作
    } else {
      ElMessage.error(response.message || '退料保存失败');
    }
  } catch (error) {
    console.error('保存退料失败:', error);
    ElMessage.error('网络错误，请稍后重试');
  } finally {
    ElLoading.service().close();
  }
};

// 组件挂载时加载数据
onMounted(async () => {
  console.log("组件挂载，开始加载数据");
  await loadCellData();
  await loadCollectMaterialsData();
  await loadRepositories();
  console.log("数据加载完成，维修退遗费数量:", collectMaterials.value.length);
});
</script>

<template>
  <div class="collect-materials-container">
    <div class="collect-materials-header">
      <el-button type="primary" @click="handleSearch">查询</el-button>
    </div>

    <div class="search-container">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input
            v-model="searchKeyword"
            placeholder="请输入搜索关键词（姓名/房号/电话）"
            clearable
            class="search-input"
            @keyup.enter="handleSearch"
          >
            <template #append>
              <el-button
                type="primary"
                icon="ep:search"
                @click="handleSearch"
              />
            </template>
          </el-input>
        </el-col>
        <el-col :span="6">
          <el-input
            v-model="contactPhone"
            placeholder="请输入联系电话"
            clearable
            class="search-input"
            @keyup.enter="handleSearch"
          />
        </el-col>
        <el-col :span="6">
          <el-select
            v-model="selectedCellId"
            placeholder="请选择小区"
            clearable
          >
            <el-option
              v-for="item in communities"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-col>
      </el-row>
    </div>

    <el-table
      v-loading="loading"
      :data="collectMaterials"
      style="width: 100%"
      border
    >
      <el-table-column prop="id" label="ID" width="80">
        <template #default="{ row }">
          <span>{{ row.id || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="cellName" label="小区" min-width="120">
        <template #default="{ row }">
          <span>{{ row.cellName || "-" }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="roomNumber" label="房号" min-width="100">
        <template #default="{ row }">
          <span>{{ row.roomNumber || "西北楼1-202" }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="contactPerson" label="联系人" min-width="100">
        <template #default="{ row }">
          <span>{{ row.contactPerson || "-" }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="contactPhone" label="联系电话" min-width="120">
        <template #default="{ row }">
          <span>{{ row.contactPhone || "-" }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" min-width="100">
        <template #default="{ row }">
          <el-tag
            size="small"
            :type="
              row.status === '待处理'
                ? 'danger'
                : row.status === '处理中'
                  ? 'warning'
                  : row.status === '已完成'
                    ? 'success'
                    : 'info'
            "
          >
            {{ row.status || "-" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="importance" label="重要程度" min-width="100">
        <template #default="{ row }">
          <el-tag
            size="small"
            :type="
              row.importance === '紧急'
                ? 'danger'
                : row.importance === '重要'
                  ? 'warning'
                  : 'info'
            "
          >
            {{ row.importance || "-" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="acceptTime" label="受理时间" min-width="150">
        <template #default="{ row }">
          <span>{{
            row.acceptTime ? new Date(row.acceptTime).toLocaleString() : "-"
          }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="requiredCompleteTime" label="要求完成时间" min-width="150">
        <template #default="{ row }">
          <span>{{
            row.requiredCompleteTime ? new Date(row.requiredCompleteTime).toLocaleString() : "-"
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="150" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" link size="small" @click="openCollectMaterialDialog(row)">
            领料
          </el-button>
          <el-button type="primary" link size="small" @click="openReturnMaterialDialog(row)">
            退料
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="prev, pager, next, jumper, sizes, total"
        :total="totalCount"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      />
    </div>
  </div>

  <!-- 领料对话框 -->
  <el-dialog
    v-model="collectMaterialDialogVisible"
    title="领料"
    width="80%"
    destroy-on-close
  >
    <div class="dialog-content">
      <div class="registration-info">
        <h3>登记信息</h3>
        <el-row :gutter="20">
          <el-col :span="6">
            <div class="info-item">
              <span class="label">小区：</span>
              <span class="value">{{ selectedRepairRecord?.cellName || 'XXX小区' }}</span>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item">
              <span class="label">房间：</span>
              <span class="value">{{ selectedRepairRecord?.roomNumber || '12-23-21' }}</span>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item">
              <span class="label">客户：</span>
              <span class="value">{{ selectedRepairRecord?.contactPerson || '李晓明' }}</span>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item">
              <span class="label">联系电话：</span>
              <span class="value">{{ selectedRepairRecord?.contactPhone || '18888888888' }}</span>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20" style="margin-top: 12px;">
          <el-col :span="6">
            <div class="info-item">
              <span class="label">要求处理事项：</span>
              <span class="value">{{ selectedRepairRecord?.content || '--' }}</span>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item">
              <span class="label">备注：</span>
              <span class="value">{{ selectedRepairRecord?.remark || '--' }}</span>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item">
              <span class="label">仓库：</span>
              <el-select
                v-model="selectedRepositoryId"
                placeholder="请选择仓库"
                style="width: 200px;"
              >
                <el-option
                  v-for="repo in repositoryList"
                  :key="repo.id"
                  :label="repo.name"
                  :value="repo.id"
                />
              </el-select>
            </div>
          </el-col>
        </el-row>
      </div>

      <div class="material-info">
        <h3>领料信息</h3>
        <el-button type="success" @click="addMaterial" style="margin-bottom: 10px;">+添加</el-button>
          <el-button type="danger" @click="batchReturnMaterial" style="margin-bottom: 10px; margin-left: 10px;">一键退料</el-button>
        
        <el-table
          :data="materialsList"
          style="width: 100%"
          border
        >
          <el-table-column prop="name" label="材料名称" min-width="120" />
          <el-table-column prop="brand" label="品牌" min-width="100" />
          <el-table-column prop="specification" label="规格型号" min-width="150" />
          <el-table-column prop="unit" label="单位" min-width="80" />
          <el-table-column prop="referencePrice" label="参考价" min-width="80">
            <template #default="{ row }">
              <span>{{ row.referencePrice || '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="stocks" label="库存" min-width="80">
            <template #default="{ row }">
              <span>{{ row.stocks || '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="quantity" label="数量" min-width="100">
            <template #default="{ row }">
              <el-input
                v-model.number="row.quantity"
                placeholder="请输入"
                type="number"
                min="0"
                style="width: 120px;"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" min-width="80" fixed="right">
            <template #default="{ row }">
              <el-button type="danger" link size="small" @click="removeMaterial(row.id)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="collectMaterialDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveCollectMaterials">保存</el-button>
      </span>
    </template>
  </el-dialog>
  
  <!-- 退料详情对话框 -->
  <el-dialog
    v-model="returnDetailDialogVisible"
    title="退料"
    width="400px"
    destroy-on-close
  >
    <div class="return-detail-dialog">
      <div class="detail-item">
        <span class="label">材料名称：</span>
        <span class="value">{{ currentReturnMaterial?.name || '' }}</span>
      </div>
      <div class="detail-item">
        <span class="label">单价：</span>
        <span class="value">{{ currentReturnMaterial?.price || 0 }}元</span>
      </div>
      <div class="detail-item">
        <span class="label">可退数量：</span>
        <span class="value">{{ currentReturnMaterial?.availableQuantity || 0 }}</span>
      </div>
      <div class="detail-item">
        <span class="label">退货数量：</span>
        <el-input-number
          v-model="inputReturnQuantity"
          :min="1"
          :max="currentReturnMaterial?.availableQuantity || 999"
          @change="updateReturnQuantity"
          style="width: 150px;"
        />
      </div>
      <div class="detail-item">
        <span class="label">退货金额：</span>
        <span class="value">{{ returnAmount.toFixed(2) }}元</span>
      </div>
    </div>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="returnDetailDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmReturnMaterial">确定</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 退料对话框 -->
  <el-dialog
    v-model="returnMaterialDialogVisible"
    title="退料"
    width="80%"
    destroy-on-close
  >
    <div class="dialog-content">
      <div class="registration-info">
        <h3>登记信息</h3>
        <el-row :gutter="20">
          <el-col :span="6">
            <div class="info-item">
              <span class="label">小区：</span>
              <span class="value">{{ selectedRepairRecord?.cellName || 'XXX小区' }}</span>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item">
              <span class="label">房间：</span>
              <span class="value">{{ selectedRepairRecord?.roomNumber || '12-23-21' }}</span>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item">
              <span class="label">客户：</span>
              <span class="value">{{ selectedRepairRecord?.contactPerson || '李晓明' }}</span>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item">
              <span class="label">联系电话：</span>
              <span class="value">{{ selectedRepairRecord?.contactPhone || '18888888888' }}</span>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20" style="margin-top: 12px;">
          <el-col :span="6">
            <div class="info-item">
              <span class="label">要求处理事项：</span>
              <span class="value">漏水</span>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item">
              <span class="label">备注：</span>
              <span class="value">--</span>
            </div>
          </el-col>
        </el-row>
      </div>

      <div class="return-material-info">
        <el-tabs v-model="activeReturnTab" type="border-card">
          <el-tab-pane label="可退材料" name="returnable">
            <el-table
              :data="returnableMaterials"
              style="width: 100%"
              border
            >
              <el-table-column prop="name" label="材料名称" min-width="120" />
              <el-table-column prop="brand" label="品牌" min-width="100" />
              <el-table-column prop="specification" label="规格型号" min-width="150" />
              <el-table-column prop="unit" label="单位" min-width="80" />
              <el-table-column prop="price" label="参考价" min-width="80">
                <template #default="{ row }">
                  <span>{{ row.price || '-' }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="quantityIssued" label="领用数量" min-width="100">
                <template #default="{ row }">
                  <span>{{ row.quantityIssued || row.usedQuantity }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="remark" label="备注" min-width="120">
                <template #default="{ row }">
                  <el-input
                    v-model="row.remark"
                    placeholder="请输入"
                    style="width: 150px;"
                  />
                </template>
              </el-table-column>
              <el-table-column label="操作" min-width="80" fixed="right">
                <template #default="{ row }">
                  <el-button type="primary" link size="small" @click="openReturnDetailDialog(row)">
                    退料
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="已退材料" name="returned">
            <el-button type="danger" @click="batchDeleteReturned" style="margin-bottom: 10px;">一键删除</el-button>
            <el-table
              :data="returnedMaterials"
              style="width: 100%"
              border
            >
              <el-table-column prop="name" label="材料名称" min-width="120" />
              <el-table-column prop="brand" label="品牌" min-width="100" />
              <el-table-column prop="specification" label="规格型号" min-width="150" />
              <el-table-column prop="unit" label="单位" min-width="80" />
              <el-table-column prop="price" label="参考价" min-width="80">
                <template #default="{ row }">
                  <span>{{ row.price || '-' }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="quantityIssued" label="领用数量" min-width="100">
                <template #default="{ row }">
                  <span>{{ row.quantityIssued || '-' }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="quantityReturned" label="已退数量" min-width="100">
                <template #default="{ row }">
                  <span>{{ row.quantityReturned || row.returnedQuantity || '-' }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="remark" label="备注" min-width="120">
                <template #default="{ row }">
                  <el-input
                    v-model="row.remark"
                    placeholder="请输入"
                    style="width: 150px;"
                    disabled
                  />
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancelReturn">取消</el-button>
        <el-button type="primary" @click="saveReturnMaterials">保存</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 材料选择对话框 -->
  <el-dialog
    v-model="materialSelectDialogVisible"
    title="选择材料"
    width="80%"
    destroy-on-close
  >
    <div class="dialog-content">
      <!-- 搜索区域 -->
      <div class="search-container" style="margin-bottom: 15px;">
        <el-input
          v-model="materialSearchKeyword"
          placeholder="请输入材料名称、品牌或规格型号"
          prefix-icon="el-icon-search"
          style="width: 300px;"
          @input="loadInventoryMaterials"
        />
      </div>

      <!-- 材料列表 -->
      <el-table
        :data="inventoryMaterials"
        style="width: 100%"
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="name" label="材料名称" min-width="120" />
        <el-table-column prop="brand" label="品牌" min-width="100" />
        <el-table-column prop="specification" label="规格型号" min-width="150" />
        <el-table-column prop="unit" label="单位" min-width="80" />
        <el-table-column prop="outboundPrice" label="参考价" min-width="80">
          <template #default="{ row }">
            <span>{{ row.outboundPrice || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="stocks" label="库存数量" min-width="100" />
      </el-table>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="materialSelectDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleMaterialSelection">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped>
.collect-materials-container {
  padding: 20px;
}

.collect-materials-header {
  margin-bottom: 20px;
}

.search-container {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 对话框样式 */
.dialog-content {
  padding: 10px 0;
}

.registration-info {
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.registration-info h3,
.material-info h3 {
  margin-bottom: 15px;
  font-size: 16px;
  font-weight: 600;
}

.info-item {
  margin-bottom: 10px;
}

.info-item .label {
  font-weight: 500;
  margin-right: 10px;
}

.material-info,
.return-material-info {
  margin-top: 20px;
}

/* 退料详情对话框样式 */
.return-detail-dialog {
  padding: 10px;
}

.return-detail-dialog .detail-item {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.return-detail-dialog .detail-item .label {
  width: 100px;
  font-weight: bold;
}

.return-detail-dialog .detail-item .value {
  color: #333;
}
</style>